package com.buss.activity.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.jweb.core.bean.PageMode;
import org.jweb.core.bean.ReplyDataMode;
import org.jweb.core.query.hibernate.qbc.CriteriaQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.buss.activity.service.ActivityUserService;
import com.buss.activity.trans.form.ActiveForm;
import com.buss.activity.trans.form.ActivityForm;
import com.buss.activity.trans.vo.ActivedetailVO;
import com.buss.activity.trans.vo.ActivityVO;
import com.buss.activity.trans.vo.UserActivityVO;
import com.buss.article.trans.vo.ArticleVO;
import com.buss.article.trans.vo.ArticledetailVO;
import com.buss.auth.transfer.vo.authen.AuthUserVO;
import com.buss.common.entity.HxActive;
import com.buss.common.entity.HxArticle;
import com.buss.common.entity.HxUserActive;
import com.buss.common.service.SysServiceI;

@Controller
@RequestMapping("/activity")
public class ActivityController {
	
	@Autowired
	private ActivityUserService activityService;
	
	@Autowired
	private SysServiceI sysService;
	
	/**
	 * 添加活动报名接口
	 * @param activityForm
	 * @return 报名成败信息
	 */
	@RequestMapping("/join")
	@ResponseBody
	public Object joinactivity(ActivityForm activityForm){
		ReplyDataMode rdm = new ReplyDataMode();	// 数据响应模型
		
		Subject currentUser = SecurityUtils.getSubject();
		AuthUserVO user = (AuthUserVO) currentUser.getSession().getAttribute("userInfo");
		String level = user.getLevelclass();
		String uid = user.getId();
		activityForm.setUid(uid);
		
		HxActive article = sysService.findUniqueByProperty(HxActive.class, "id", Long.parseLong(activityForm.getAid()));
		
		String dataString = article.getPublishTime();
		if(StrToDate(dataString).before(new Date())){
			rdm.setStatusCode("200");
			rdm.setSuccess(true);
			rdm.setData("该活动已过期，不能报名！");
		}else if(article.getLevelclass()>Integer.parseInt(level)) {
			rdm.setStatusCode("200");
			rdm.setSuccess(true);
			rdm.setData("您的等级不够，请升级会员！");
		} else {
//			activityForm.setCheckstatus(checkstatus);
			
			try {
				CriteriaQuery cq = activityForm.getCriteriaQuery();
				List list = activityService.list(cq);
				if(list!=null && list.size()>0) {
					HxUserActive userArticle = (HxUserActive) list.get(0);
					userArticle.setIsDelete(0);
					activityService.saveOrUpdate(userArticle);
					rdm.setStatusCode("200");
					rdm.setSuccess(true);
					rdm.setData("报名成功");
//					activityService.updateEntitie(article);
				} else {
					activityForm.setIsDelete(0+"");// 数据有效性
					activityService.saveOrUpdate(activityForm.toEntity());
					rdm.setStatusCode("200");
					rdm.setSuccess(true);
					rdm.setData("报名成功");
				}
			} catch (Exception e) {
				rdm.setStatusCode("200");
				rdm.setSuccess(true);
				rdm.setData("报名失败");
			}
			
		}
		

		return rdm;
	}
	
	/**
	 * 查看 报名的活动
	 * uid 根据userid查询数据库
	 */
	@RequestMapping("/findActivity")
	@ResponseBody
	public Object activityByUid(ActivityForm activityForm) {
		Subject currentUser = SecurityUtils.getSubject();
		AuthUserVO user = (AuthUserVO) currentUser.getSession().getAttribute("userInfo");
		String level = user.getLevelclass();
		String uid = user.getId();

		activityForm.setUid(uid);
		activityForm.setStatus("1");
		
		ReplyDataMode dataMode = new ReplyDataMode();
		CriteriaQuery cq = activityForm.getCriteriaQuery();
		
		int pageNo = Integer.parseInt(activityForm.getPageNo());
		int pageSize = Integer.parseInt(activityForm.getPageSize());
		
		PageMode userArticles = this.activityService.list4page(cq, pageNo, pageSize);
		List<HxUserActive> uas = userArticles.getResult();
		List<UserActivityVO> articleVOs = new ArrayList<>();
		UserActivityVO articleVO = null;
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		for(HxUserActive ua : uas) {
			articleVO = new UserActivityVO();
			articleVO.copyEntity(ua);
			if(ua.getHxActive().getPublishTime() != null) {
				  articleVO.setPublishTime(dateFormat.format(StrToDate(ua.getHxActive().getPublishTime()))); }
			articleVOs.add(articleVO);
		}
		userArticles.setResult(articleVOs);
		
		dataMode.setData(userArticles);
		
		return dataMode;
	}
	/**
	 * 取消报名
	 * aid 活动id
	 * uid 用户id
	 */
	@RequestMapping("/cancelActivity")
	@ResponseBody
	public Object cancelActivity(ActivityForm activityForm){
		Subject currentUser = SecurityUtils.getSubject();
		AuthUserVO user = (AuthUserVO) currentUser.getSession().getAttribute("userInfo");
		String level = user.getLevelclass();
		String uid = user.getId();
		activityForm.setUid(uid);
		ReplyDataMode rdm = new ReplyDataMode();	// 数据响应模型
		
		try {
			CriteriaQuery cq = activityForm.getCriteriaQuery();
			List list = activityService.list(cq);
			if(list!=null && list.size()>0) {
				HxUserActive userArticle = (HxUserActive) list.get(0);
				activityService.delete(userArticle);
				rdm.setStatusCode("200");
				rdm.setSuccess(true);
				rdm.setData("取消报名成功");
			} else {
				rdm.setStatusCode("500");
				rdm.setSuccess(true);
				rdm.setData("您传参数有误");
			}
//			userArticle.setIsDelete(1);// 数据有效性
//			activityService.saveOrUpdate(userArticle);
			
		} catch (Exception e) {
			rdm.setStatusCode("200");
			rdm.setSuccess(true);
			rdm.setData("取消报名失败");
		}
		
		return rdm;
	}
	/**
	 * 活动显示接口
	 * 
	 */
	@RequestMapping("/activitys")
	@ResponseBody
	public Object activitys(ActiveForm activityForm) {
		ReplyDataMode dataMode = new ReplyDataMode();
		activityForm.setStatus("1");
		CriteriaQuery cq = activityForm.getCriteriaQuery();
		Map< String, Object> orderby = new HashMap<>();
		orderby.put("createTime", "desc");
		cq.setOrder(orderby);
		int pageNo = Integer.parseInt(activityForm.getPageNo());
		int pageSize = Integer.parseInt(activityForm.getPageSize());
		
		PageMode userArticles = sysService.list4page(cq, pageNo, pageSize);
		List<HxActive> uas = userArticles.getResult();
		List<ActivityVO> articleVOs = new ArrayList<>();
		ActivityVO articleVO = null;
		for(HxActive ua : uas) {
			System.out.println(ua.getActives().size());
			articleVO = new ActivityVO();

			List<HxActive> uu = ua.getActives();
			List<HxActive> ur = new ArrayList();
			for (HxActive child  : uu) {
				if (child.getStatus() == 1) {
					ur.add(child);
				}
			}
			ua.setActives(ur);
			articleVO.copyEntity(ua);
		
			articleVOs.add(articleVO);
		}
		userArticles.setResult(articleVOs);
		dataMode.setSuccess(true);
		dataMode.setData(userArticles);
		
		return dataMode;
	}
	@RequestMapping({ "/byIdContent.do" })
	@ResponseBody
	public ReplyDataMode byIdContent(HttpServletRequest request)
			throws ServletException, IOException {
		ReplyDataMode j = new ReplyDataMode();
		List<HxActive> entityList = null;
		
		String id = request.getParameter("id");
		if(id!=null&&id!=""){			
			entityList = sysService.findByProperty(HxActive.class, "id", Long.parseLong(id));
		}
		
		Subject currentUser = SecurityUtils.getSubject();
		AuthUserVO user = (AuthUserVO) currentUser.getSession().getAttribute("userInfo");
		List<HxUserActive> userActives = null;
		if(user != null){
			String level = user.getLevelclass();
			String uid = user.getId();
			
			ActivityForm activityForm = new ActivityForm();
			activityForm.setAid(id);
			activityForm.setUid(uid);
			activityForm.setStatus("0");
			userActives = activityService.list(activityForm.getCriteriaQuery());
		}
		
		List<ActivedetailVO> articleVOs = new ArrayList<>();
		ActivedetailVO articleVO = null;
		for(HxActive e : entityList){
			articleVO = new ActivedetailVO();
			articleVO.copyEntity(e);
			String dataString = e.getPublishTime();
			if(userActives!=null && userActives.size()>0) {
				articleVO.setFriday("1");// 您已报名
			}
			if(StrToDate(dataString).before(new Date())){
				
				articleVO.setFriday("2"); // 该活动已过期
			} 
			articleVOs.add(articleVO);
		}
		
		j.setData(articleVOs);
		j.setStatusCode("200");
		j.setSuccess(true);
		
		return j;
	}
	/**
	* 字符串转换成日期
	* @param str
	* @return date
	*/
	public static Date StrToDate(String str) {
	  
	   SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	   Date date = null;
	   try {
	    date = format.parse(str);
	   } catch (Exception e) {
	    e.printStackTrace();
	   }
	   return date;
	}
	
	public static void main(String[] args) {
		Date today = new Date();
		System.out.println(StrToDate("2016-4-21 24:00:00").before(today));
	}
}
